package umage.action;

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JOptionPane;

import org.jhotdraw.app.Project;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.Figure;

import umage.figures.TransitionFigure;
import umage.projects.UMageProject;

@ActionInfo(name = "Fire Random Transition", menu = "Petri Net")
public class FireRandomTransitionAction extends DefaultAction {

	@Override
	public void actionPerformed(ActionEvent e) {
		Project p = getApplication().getCurrentProject();
		if (p == null || !(p instanceof UMageProject)) return;
		Drawing d = ((UMageProject)p).getDrawingEditor().getView().getDrawing();
		
		ArrayList<TransitionFigure> firableTransitions = new ArrayList<TransitionFigure>();
		
		// Find out which transitions can be fired at this time
		for (Figure figure : d.getFigures()) {
			if (figure instanceof TransitionFigure) {
				TransitionFigure testTransition = (TransitionFigure)figure;
				if (testTransition.canFire()) firableTransitions.add(testTransition);
			}
		}
		
		// Display a message if there are no transitions which can be fired
		if (firableTransitions.size() == 0) {
			JOptionPane.showMessageDialog(null, "There are currently no transitions which meet the requirements to fire", "No firable transitions", JOptionPane.INFORMATION_MESSAGE);
			return;
		}
		
		// Fire off an available transition at random
		firableTransitions.get(new Random().nextInt(firableTransitions.size())).fire();
		
	}

}
